import axios from 'axios'
import {ElMessage} from 'element-plus'
import messauthManager from './user'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const getBaseURL = () => {
    const BASEURL = window['HISS_URL'] || 'http://localhost:8081/';
    console.log('初始化服务器地址：',BASEURL)
    return BASEURL
}
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: getBaseURL(),
    // 超时
    timeout: 10000
})

// request拦截器
service.interceptors.request.use(config => {
    config.baseURL = getBaseURL()
    // 透传 token
    const header = config.headers || {}
    let token = messauthManager.getToken();
    header.token = token
    config.headers = header
    // 重置认证数据
    if (config.url === '/v1/receiver') {
        const data = config.data
        const parmsData = data.messageAuth || {}
        const localData = messauthManager.getMessageAuth()
        const palyload = data.palyload || {}
        const messageAuth = {
            tenant : palyload['_tenant'] || localData['tenant'] || parmsData['tenant'],
            currentUser: localData['currentUser'] || parmsData['currentUser']
        }
        data.messageAuth = messageAuth
        config.data = data
    }
    return config
}, error => {
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 200;
        // 获取错误信息
        const msg = res.data.errorMessage || '位置错误错误'+code;
        return res.data
    },
    error => {
        let msg = error.message;
        console.log(error)
        if(error.code=='ECONNABORTED'){
            ElMessage.error(msg);
        }
        let {message} = error;
        return Promise.reject(error)
    }
)

export default service
